<template>
  <div class="grade-detail-container">
    <!-- 内容主体 -->
    <div class="content">
      <!-- 加载状态 -->
      <div
        v-if="loading"
        class="bg-white p-4 rounded-md shadow mb-4"
      >
        <div
          class="spinner-border text-primary"
          role="status"
        >
          <span class="visually-hidden">Loading...</span>
        </div>
        <p class="mt-2 text-sm text-gray-500">
          加载练习详情中，请稍候...
        </p>
      </div>

      <!-- 错误提示 -->
      <div
        v-else-if="error"
        class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded-md mb-4"
      >
        <span>{{ error }}</span>
        <button 
          class="ml-4 btn btn-sm btn-primary" 
          @click="fetchExerciseDetails"
        >
          重试
        </button>
      </div>

      <!-- 详情内容 -->
      <div
        v-else-if="exercise"
        class="space-y-6"
      >
        <div class="flex justify-between items-center mb-6">
          <h2 class="text-xl font-bold">
            {{ exercise.exerciseName }}
          </h2>
          <div class="flex items-center gap-4">
            <p class="text-sm text-gray-500">
              学生: {{ studentName }}
            </p>
            <p class="text-sm text-gray-500">
              当前总分: {{ totalScore }} / {{ exercise.exerciseScore }}分
            </p>
          </div>
        </div>

        <div v-if="questionsWithAnswers.length > 0">
          <div
            v-for="(question, index) in questionsWithAnswers"
            :key="question.question.questionId"
            class="mb-6"
          >
            <div class="border rounded-md p-4 text-left">
              <!-- 添加左对齐类 -->
              <h3 class="text-lg font-medium mb-2">
                题目 {{ index + 1 }} ({{ question.question.questionScore }}分)
              </h3>
              <div class="mb-3">
                <p
                  class="text-gray-700"
                  v-html="parseQuestionContent(question.question.questionContent)"
                />
              </div>

              <div class="flex gap-4">
                <!-- 学生答案 -->
                <div class="w-1/2">
                  <h4 class="text-sm font-medium text-gray-600 mb-2">
                    学生答案:
                  </h4>
                  <div class="bg-gray-100 p-3 rounded-md">
                    <p
                      v-if="question.studentAnswer.studentAnswer"
                      v-html="parseLineBreaks(question.studentAnswer.studentAnswer)"
                    />
                    <p
                      v-else
                      class="text-gray-500"
                    >
                      未提交答案
                    </p>
                  </div>
                </div>

                <!-- 正确答案 & 评分 -->
                <div class="w-1/2">
                  <h4 class="text-sm font-medium text-gray-600 mb-2">
                    正确答案:
                  </h4>
                  <div class="bg-green-100 p-3 rounded-md">
                    <p v-html="parseLineBreaks(question.question.questionAnswer)" />
                  </div>

                  <h4 class="text-sm font-medium text-gray-600 mt-4">
                    设置得分:
                  </h4>
                  <input 
                    v-model="question.studentAnswer.gainScore" 
                    type="number" 
                    :min="0" 
                    :max="question.question.questionScore" 
                    class="w-full p-2 border rounded-md mt-2"
                  >
                </div>
              </div>
            </div>
          </div>
        </div>
        <div
          v-else
          class="bg-white p-4 rounded-md text-center"
        >
          <p class="text-lg text-gray-600">
            该练习暂无题目
          </p>
        </div>

        <div class="mt-8 text-right">
          <button 
            class="btn btn-primary mr-4" 
            :disabled="isSubmitting || !isValidScore"
            @click="submitGrades"
          >
            {{ isSubmitting ? '提交中...' : '提交批改结果' }}
          </button>
        </div>
      </div>

      <!-- 无数据提示 -->
      <div
        v-else
        class="bg-white p-4 rounded-md text-center"
      >
        <p class="text-lg text-gray-600">
          未找到练习详情
        </p>
      </div>
    </div>

    <!-- 返回按钮（底部固定位置） -->
    <button 
      class="btn btn-dark close-btn" 
      style="position: fixed; bottom: 2rem; left: 50%; transform: translateX(-50%);"
      @click="$emit('close')"
    >
      <i class="fa fa-chevron-left me-1" /> 返回练习列表
    </button>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  name: 'GradeExerciseDetail',
  props: {
    exerciseId: { type: String, required: true },
    studentId: { type: String, required: true },
    classesId: { type: String, required: true }
  },
  data() {
    return {
      exercise: null,
      studentName: '',
      questionsWithAnswers: [],
      totalScore: 0,
      isSubmitting: false,
      error: null,
      loading: true
    };
  },
  computed: {
    isValidScore() {
      if (this.questionsWithAnswers.length === 0) return true;
      return this.questionsWithAnswers.every(q => 
        q.studentAnswer.gainScore >= 0 && 
        q.studentAnswer.gainScore <= q.question.questionScore
      );
    }
  },
  watch: {
    exerciseId(newVal) {
      if (newVal) this.fetchExerciseDetails();
    }
  },
  mounted() {
    this.fetchExerciseDetails();
  },
  methods: {
    async fetchExerciseDetails() {
      this.loading = true;
      this.error = null;
      try {
        const response = await axios.get(`/api/exercises/${this.exerciseId}/grading/${this.studentId}`);
        const data = response.data;
        if (!data || !data.exercise || !data.studentExercise || !Array.isArray(data.questions)) {
          throw new Error('接口返回数据不完整，缺少必要字段');
        }
        const { exercise, studentExercise, questions } = data;
        this.exercise = exercise;
        this.studentName = studentExercise.user.userName;
        this.totalScore = studentExercise.studentScore;
        this.questionsWithAnswers = questions.map(q => ({ ...q, studentAnswer: q.studentAnswer || { gainScore: 0 } }));
      } catch (error) {
        console.error('[错误] 获取练习详情失败:', error.message);
        this.error = error.message || '加载练习详情失败，请重试';
      } finally {
        this.loading = false;
      }
    },

    async submitGrades() {
      if (this.isSubmitting) return;
      this.isSubmitting = true;
      try {
        if (this.questionsWithAnswers.length === 0) throw new Error('无有效题目数据，无法提交');
        const grades = this.questionsWithAnswers.map(q => ({ 
          id: { userId: this.studentId, questionId: q.question.questionId, exerciseId: this.exerciseId },
          gainScore: q.studentAnswer.gainScore 
        }));
        await axios.post('/api/exercises/grading/submit', { 
          exerciseId: this.exerciseId,
          studentId: this.studentId,
          totalScore: this.questionsWithAnswers.reduce((sum, q) => sum + q.studentAnswer.gainScore, 0),
          grades: grades 
        });
        alert('批改成功！');
        this.$emit('close');
        this.$emit('refresh');
      } catch (error) {
        console.error('[错误] 提交批改失败:', error.message);
        this.error = '提交失败，请检查分数是否正确';
      } finally {
        this.isSubmitting = false;
      }
    },

    parseLineBreaks(text) {
      return text ? text.replace(/\n/g, '<br>') : '';
    },

    parseQuestionContent(content) {
      return content ? content.split(/\n[A-Za-z]\./)[0] + '<br>' : '';
    }
  }
};
</script>

<style scoped>
.grade-detail-container {
  position: relative;
  min-height: 100vh;
  padding: 2rem;
  max-width: 100%;
  margin: 0 auto;
}

.content {
  max-width: 800px;
  margin: 0 auto;
}

/* 深色按钮样式 */
.btn-dark {
  background-color: #374151; /* 深灰色 */
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.btn-dark:hover {
  background-color: #252e3c; /* 更深的灰色 */
}

/* 题目内容左对齐 */
.text-left {
  text-align: left;
}
</style>
